package com.sky.service.impl;

import com.sky.dto.GoodsSalesDTO;
import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import com.sky.mapper.UserMapper;
import com.sky.service.ReportService;
import com.sky.service.WorkspaceService;
import com.sky.vo.*;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * com.sky.service
 * ReportService
 *
 * @since 2024/11/12
 */
@Service
public class ReportServiceImpl implements ReportService {
    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private WorkspaceService workspaceService;;

    /**
     * 根据时间区间统计营业额
     * @param begin
     * @param end
     * @return
     */
    public TurnoverReportVO turnoverStatistics(LocalDate begin, LocalDate end) {
        List<LocalDate> dateList = new ArrayList<>();
        dateList.add(begin);

        while (!begin.equals(end)){
            begin = begin.plusDays(1);//日期计算，获得指定日期后1天的日期
            dateList.add(begin);
        }

        List<Double> turnoverList = new ArrayList<>();
        for (LocalDate date : dateList) {
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);
            Map map = new HashMap();
            map.put("status", Orders.COMPLETED);
            map.put("begin",beginTime);
            map.put("end", endTime);
            Double turnover = orderMapper.selectTurnoverByDates(map);
            turnover = turnover == null ? 0.0 : turnover;
            turnoverList.add(turnover);
        }

        //数据封装
        return TurnoverReportVO.builder()
                .dateList(StringUtils.join(dateList,","))
                .turnoverList(StringUtils.join(turnoverList,","))
                .build();
    }

    /**
     * 用户统计
     * @param begin
     * @param end
     * @return
     */
    public UserReportVO userStatistics(LocalDate begin, LocalDate end) {
        // 获取期间日期
        List<LocalDate> dateList = new ArrayList<>();
        dateList.add(begin);

        while (!begin.equals(end)){
            begin = begin.plusDays(1);//日期计算，获得指定日期后1天的日期
            dateList.add(begin);
        }

        // 通过日期获取用户新增数和总用户
        List<Integer> newUserList = new ArrayList<>(); //新增用户数
        List<Integer> totalUserList = new ArrayList<>(); //总用户数

        dateList.forEach(time ->{
            LocalDateTime beginTime = LocalDateTime.of(time, LocalTime.MIN); // 时间最小值
            LocalDateTime endTime = LocalDateTime.of(time, LocalTime.MAX); // 时间最大值
            Map map = new HashMap();
            // 总用户数
            map.put("end", endTime);
            Integer totalUser = userMapper.getUserCount(map);
            // 新增用户数
            map.put("begin",beginTime);
            Integer newUser = userMapper.getUserCount(map);
            totalUserList.add(totalUser);
            newUserList.add(newUser);
        });
        return UserReportVO.builder()
                .dateList(StringUtils.join(dateList,","))
                .newUserList(StringUtils.join(newUserList,","))
                .totalUserList(StringUtils.join(totalUserList,","))
                .build();
    }

    /**
     * 订单统计
     * @param begin
     * @param end
     * @return
     */
    public OrderReportVO ordersStatistics(LocalDate begin, LocalDate end) {
        // 存放日期区间
        List<LocalDate> dateList = new ArrayList<>();
        dateList.add(begin);
        while (!begin.equals(end)) {
            begin = begin.plusDays(1);
            dateList.add(begin);
        }
        Map<String, Object> map = new HashMap<>();

        // 思路:
        // 1. 查询每日订单数和每日有效订单数 通过 end 查询当天
        // 每日订单数
        List<Integer> orderCountList = new ArrayList<>();
        // 每日有效订单数
        List<Integer> validOrderCountList = new ArrayList<>();
        dateList.forEach(time -> {
            LocalDateTime beginTime = LocalDateTime.of(time, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(time, LocalTime.MAX);
            map.put("begin", beginTime);
            map.put("end", endTime);

            // 查询每日订单数
            Integer orderCount = orderMapper.getOrderCount(map);
            orderCountList.add(orderCount);

            // 查询每日有效订单数
            map.put("status", Orders.COMPLETED);
            Integer validOrderCount = orderMapper.getOrderCount(map);
            validOrderCountList.add(validOrderCount);

            // 清除 status 参数，以便下一次查询总订单数时不带 status
            map.remove("status");
        });

        // 2. 查询dateList日期的订单总数,以及有效订单数 2. 计算订单完成率
        Integer totalOrderCount = orderCountList.stream().reduce(Integer::sum).orElse(0);
        Integer validOrderCount = validOrderCountList.stream().reduce(Integer::sum).orElse(0);

        // 计算订单完成率
        double orderCompletionRate = totalOrderCount == 0 ? 0 : (double) validOrderCount / totalOrderCount;

        return OrderReportVO.builder()
                .dateList(StringUtils.join(dateList, ","))
                .orderCountList(StringUtils.join(orderCountList, ","))
                .validOrderCountList(StringUtils.join(validOrderCountList, ","))
                .totalOrderCount(totalOrderCount)
                .validOrderCount(validOrderCount)
                .orderCompletionRate(orderCompletionRate)
                .build();
    }

    /**
     * 销量排名TOP10
     * @param begin
     * @param end
     * @return
     */
    public SalesTop10ReportVO top10(LocalDate begin, LocalDate end) {
        LocalDateTime beginTime = LocalDateTime.of(begin, LocalTime.MIN);
        LocalDateTime endTime = LocalDateTime.of(end, LocalTime.MAX);
        //select od.name,sum(od.number) from order_detail od,orders o where od.order_id = o.id and o.status = 5
        //and o.order_time > '2024-10-12' and o.order_time < '2024-11-12' group by od.name
        List<GoodsSalesDTO> dtoList = orderMapper.getGoodsSales(beginTime,endTime);
        List<String> nameList = new ArrayList<>();
        List<Integer> numberList = new ArrayList<>();
        dtoList.forEach(goods ->{
            nameList.add(goods.getName());
            numberList.add(goods.getNumber());
        });
        String names = StringUtils.join(nameList, ",");
        String numbers = StringUtils.join(numberList, ",");
        return SalesTop10ReportVO.builder()
                .nameList(names)
                .numberList(numbers)
                .build();
    }

    /**
     * 导出运营Excel报表
     * @param response
     */
    public void exportExcel(HttpServletResponse response) {
        LocalDate begin = LocalDate.now().minusDays(30);
        LocalDate end = LocalDate.now();
        LocalDateTime beginTime = LocalDateTime.of(begin, LocalTime.MIN);
        LocalDateTime endTime = LocalDateTime.of(end, LocalTime.MAX);
        // 查询营业额数据
        BusinessDataVO businessData = workspaceService.getBusinessData(beginTime, endTime);

        // 导入Excel模板
        InputStream resource = this.getClass().getClassLoader().getResourceAsStream("template/运营数据报表模板.xlsx");

        // 基于模板文件创建新的Excel文件
        try {
            XSSFWorkbook excel = new XSSFWorkbook(resource);

            // 填充数据
            XSSFSheet sheet = excel.getSheet("Sheet1"); //获取Sheet标签页
            // 获得第二行 第二个单元格-> 时间
            sheet.getRow(1).getCell(1).setCellValue("时间："+begin+"至"+end); // 时间

            // 获得第四行 第三个单元格 -> 营业额
            XSSFRow row = sheet.getRow(3);
            row.getCell(2).setCellValue(businessData.getTurnover());
            // 第五个单元格 -> 订单完成率
            row.getCell(4).setCellValue(businessData.getOrderCompletionRate());
            // 第七个单元格 -> 新增用户数
            row.getCell(6).setCellValue(businessData.getNewUsers());

            // 获得第五行 第三个单元格 -> 有效订单
            row = sheet.getRow(4);
            row.getCell(2).setCellValue(businessData.getValidOrderCount());
            // 第五个单元格 -> 平均客单价
            row.getCell(4).setCellValue(businessData.getUnitPrice());

            for(int i=0;i<30;i++){
                LocalDate time = begin.plusDays(i);
                // 获取当天营业额
                businessData = workspaceService.getBusinessData(LocalDateTime.of(time, LocalTime.MIN), LocalDateTime.of(time, LocalTime.MAX));
                // 获得第七行 第三个单元格 -> 有效订单
                row = sheet.getRow(7+i);
                row.getCell(1).setCellValue(time.toString()); // 日期
                row.getCell(2).setCellValue(businessData.getTurnover()); // 营业额
                row.getCell(3).setCellValue(businessData.getValidOrderCount()); // 有效订单
                row.getCell(4).setCellValue(businessData.getOrderCompletionRate()); // 订单完成率
                row.getCell(5).setCellValue(businessData.getUnitPrice()); // 平均客单价
                row.getCell(6).setCellValue(businessData.getNewUsers()); // 新增用户数
            }
            ServletOutputStream stream = response.getOutputStream();
            excel.write(stream);

            //关闭资源
            stream.flush();
            stream.close();
            excel.close();

        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

}
